import fs from 'fs';
import log from 'electron-log';
import path from 'path';
import { app } from 'electron';
import DamiHelper from './damiSdk';
import SpyHelper from './spyHelper';
import { getIP } from './apis/remoteIp';
import SpyConfig from './config';
import qrDecode from '../utils/qrcode';
// import SpyConfig from './config';

const RESOURCES_PATH = app.isPackaged
    ? path.join(process.resourcesPath, '')
    : path.join(__dirname, '../../');

class UserHelper {
    private damiHelper: DamiHelper;
    private config: SpyConfig;
    constructor(config: SpyConfig) {
        this.config = config;
        this.damiHelper = new DamiHelper();
    }
    login(projectId: string, name: string, password: string) {
        return this.damiHelper.login(projectId, name, password);
    }
    async getUser(userCount: number, isProxy: boolean) {
        const dir = `${RESOURCES_PATH}/userData`;

        if (!fs.existsSync(dir)){
            fs.mkdirSync(dir);
        }
        const files = fs.readdirSync(dir);
        if (files.length < userCount) {
            const createNum = userCount - files.length;
           await this.createUserList(createNum, isProxy);
        }

        const newFiles = fs.readdirSync(dir);
        const userList: any[] = [];
        if (!this.damiHelper.isLogin()) {
            throw new Error('请先登录大米！');
        }
        for (let i =0;i < newFiles.length; i++) {
            // const content = fs.readFileSync(`${dir}/${files[i]}`);
            // const userInfo = JSON.parse(content.toString());
            userList.push({ userId: newFiles[i] });
        }

        return userList;
    }

    async createUserList(num: number, isProxy: boolean) {
        const promiseList: any = [];
        for (let i = 0; i < num;i++) {
            promiseList.push(this.createUser(isProxy));
        }
        return Promise.all(promiseList);
    }

    async createUser(isProxy: boolean) {
        let ip = '';
        if (isProxy) {
            ip = await this.getIP();
        }
        const spyHelper = new SpyHelper(this.config);
        await spyHelper.init(ip);
        const qrCode = await spyHelper.getQrCode();
        if (!qrCode) {
            throw new Error('没有获取到qrcode');
        }
        const url = await qrDecode(qrCode);
        await this.damiHelper.createTask(url);
        await spyHelper.saveCookie();
    };

    async getIP(): Promise<string> {
        try {
          const ipRes = await getIP(1);
          if (ipRes.data.code === 200) {
            const ipObj = ipRes.data.data[0];
            // ipObj.ip  ipObj.port
            return `${ipObj.ip}:${ipObj.port}`;
          }
        } catch (error) {
            log.info(JSON.stringify(error));
        }

        return '';
    }
}

export default UserHelper;